<route lang="json5" type="page">
{
  "needLogin": true,
  "style": {
    "navigationBarTitleText": "预警值设置"
  }
}
</route>

<script lang="ts" setup>
import { ref } from 'vue'

// 定义表项的类型
interface Meter {
  id: number
  name: string
  value: number
  unit: string
}

// 模拟水表数据
const waterMeters = ref<Meter[]>([
  { id: 1, name: 'A-501', value: 5, unit: '吨' },
  { id: 2, name: 'b-520', value: 10, unit: '吨' },
  { id: 3, name: 'A区-502', value: 15, unit: '吨' },
])

// 模拟电表数据
const electricMeters = ref<Meter[]>([
  { id: 4, name: 'A501', value: 20, unit: '度' },
  { id: 5, name: 'A502', value: 40, unit: '度' },
  { id: 6, name: 'B501', value: 60, unit: '度' },
])

const showPopup = ref(false)
const editingMeter = ref<Meter | null>(null)
const newWarningValue = ref('')

function showEditDialog(meter: Meter) {
  editingMeter.value = meter
  newWarningValue.value = String(meter.value)
  showPopup.value = true
}

function handleConfirm() {
  if (editingMeter.value && newWarningValue.value && !Number.isNaN(Number(newWarningValue.value))) {
    editingMeter.value.value = Number(newWarningValue.value)
    uni.showToast({
      title: '设置成功',
      icon: 'success',
    })
  }
  else {
    uni.showToast({
      title: '请输入有效的数字',
      icon: 'none',
    })
  }
  showPopup.value = false
}
</script>

<template>
  <view class="min-h-screen py-3">
    <!-- 水表 -->
    <wd-card title="水表">
      <wd-cell-group :border="false">
        <wd-cell
          v-for="meter in waterMeters"
          :key="meter.id"
          :title="meter.name"
          :value="`${meter.value}${meter.unit}`"
          is-link
          @click="showEditDialog(meter)"
        />
      </wd-cell-group>
    </wd-card>

    <!-- 电表 -->
    <wd-card title="电表" custom-class="mt-3">
      <wd-cell-group :border="false">
        <wd-cell
          v-for="meter in electricMeters"
          :key="meter.id"
          :title="meter.name"
          :value="`${meter.value}${meter.unit}`"
          is-link
          @click="showEditDialog(meter)"
        />
      </wd-cell-group>
    </wd-card>

    <!-- 编辑预警值弹窗 -->
    <wd-popup v-model="showPopup" position="bottom" :safe-area-inset-bottom="true">
      <view class="p-4">
        <view class="mb-4 flex items-center justify-between">
          <wd-button type="text" @click="showPopup = false">
            取消
          </wd-button>
          <text class="font-bold">
            请输入预警值
          </text>
          <wd-button type="text" custom-class="!text-blue-500" @click="handleConfirm">
            确定
          </wd-button>
        </view>
        <wd-input
          v-model="newWarningValue"
          label="预警值"
          placeholder="请输入预警值"
          type="number"
          clearable
        />
      </view>
    </wd-popup>
  </view>
</template>

<style lang="scss" scoped></style>
